import React, { useEffect,useState } from 'react'
import axios from 'axios'
axios.defaults.baseURL = "http://127.0.0.1:3000/"

export default function Add(){
    const [cate,setCate] = useState([])
    const [manner,setManner] = useState([])
    const [name,setName] = useState('')
    const [img,setImg] = useState('')
    const [distance,setDistance] = useState('')
    const [c,setC] = useState('')
    const [m,setM] = useState('')
    

    const getCate = async() => {
        let {data:{code,cate}}=await axios.get('/cate')
        if(code === 200){
            setCate(cate)
        }
    }

    const getManner = async() => {
        let {data:{code,manner}}=await axios.get('/manner')
        if(code === 200){
            setManner(manner)
        }
    }

    const add = async() => {
        let obj = {name:name,img:img,distance:distance,cate:c,manner:m}
        let {data:{code}}=await axios.post('/add',obj)
        if(code === 200){
            alert("添加成功")
            setName("")
            setImg("")
            setDistance("")
        }
    }

    

    useEffect(()=>{
        getCate()
        getManner()
    },[])

    return(
        <div>
            <select onClick={(i)=>setC(i.target.value)}>
                {
                    cate.map((item)=>{
                        return <option key={item._id} value={item._id}>{item.name}</option>
                    })
                }
            </select><br></br>
            <select onClick={(i)=>setM(i.target.value)}>
                {
                    manner.map((item)=>{
                        return <option key={item._id} value={item._id}>{item.name}</option>
                    })
                }
            </select><br></br>
            <input value={name}
            onChange={(i)=>setName(i.target.value)}
            placeholder='请输入名称'
            ></input><br></br>
            <input value={img}
            onChange={(i)=>setImg(i.target.value)}
            placeholder='请输入图片路径'
            >
            </input><br></br>
            <input
            value={distance}
            onChange={(i)=>setDistance(i.target.value)}
            placeholder='请输入距离'
            ></input><br></br>
            <button onClick={()=>add()}>添加</button>
        </div>
    )
}